package com.jiantong.web.open.app.version;

import com.google.common.collect.Maps;
import com.jiantong.version.model.Dictionary;
import com.jiantong.version.service.DictionaryReadService;
import com.jiantong.web.core.enums.ExceptionCode;
import io.terminus.boot.rpc.common.annotation.RpcConsumer;
import io.terminus.common.model.Response;
import io.terminus.pampas.openplatform.annotations.OpenBean;
import io.terminus.pampas.openplatform.annotations.OpenMethod;
import io.terminus.pampas.openplatform.exceptions.OPClientException;
import io.terminus.pampas.openplatform.exceptions.OPServerException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.List;
import java.util.Map;

/**
 * Created by mz on 25/8/17.
 *
 */
@Slf4j
@OpenBean
public class DictionaryApis {

    @RpcConsumer
    private DictionaryReadService dictionaryReadService;

    @OpenMethod(
            key = "find.dictionary.list.by.type",
            paramNames = {"type"},
            httpMethods = RequestMethod.GET
    )
    public List<Dictionary> findListByType(Integer type){
        if(type == null){
            log.error("type must be not null");
            throw new OPClientException(ExceptionCode.PARAMETER_NOT_EXIST.value(),"type must be not null");
        }

        Response<List<Dictionary>> response = dictionaryReadService.findListByType(type);

        if(!response.isSuccess()){
            log.error("failed to find list by type , case = {}",response.getError());
            throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),response.getError());
        }

        return response.getResult();
    }


    @OpenMethod(
            key = "find.dictionary.all",
            httpMethods = RequestMethod.GET
    )
    public Map<String,Map<Integer,String>> findAll(){

        Response<List<Dictionary>> response = dictionaryReadService.findAll();

        if(!response.isSuccess()){
            log.error("failed to find all dictionary",response.getError());
            throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),response.getError());
        }

        Map<String ,Map<Integer , String>> dictionaryMap = Maps.newHashMap();

        List<Dictionary> list = response.getResult();
        for(Dictionary dictionary : list){
            dictionaryMap.put(dictionary.getTypeName(),dictionary.getCodeNameMap());
        }
        return dictionaryMap;
    }
}
